<template>
	<div class="getCode">
		<div class="phone">
			<u-input placeholder="请输入手机号" v-model="modelValue" :maxlength="11"></u-input>
			<u-toast ref="uToast"></u-toast>
			<u-verification-code :seconds="seconds" @end="end" @start="start" ref="uCode" @change="codeChange"></u-verification-code>
			<u-button type="primary" :custom-style="customStyle" @tap="getCode">{{ tips }}</u-button>
		</div>
		<div class="code">
			<u-input v-if="codeVisible" placeholder="请输入验证码" v-model="code"></u-input>
		</div>
	</div>
</template>

<script>
import mixin from "@/mixin"
import { code } from "@/uni/uni.js"
import dayjs from "dayjs"
export default {
	name: "vGetCode",
	mixins: [mixin],
	model: {
		prop: "value",
		event: "update:value",
	},
	created() {
		this.tbId = window.location.search.slice(4)
	},
	props: {
		value: {
			type: String,
			default: "",
		},
		seconds: {
			type: Number,
			default: 60,
		},
		validMinutes: {
			type: Number,
			default: 5,
		},
	},
	data() {
		return {
			tbId: "",
			code: "",
			tips: "",
			codeVisible: false,
			// refCode: null,
			customStyle: {
				fontSize: "26rpx",
				height: "60rpx",
				padding: "0rpx 30rpx",
			},
		}
	},

	components: {},

	computed: {
		modelValue: {
			get() {
				return this.value
			},
			set(val) {
				this.$emit("update:value", val)
			},
		},
	},

	methods: {
		codeChange(text) {
			// if (!this.phone) {
			// 	this.$u.toast("请输入手机号")
			// 	return
			// }
			this.tips = text
		},
		getCode() {
			if (!this.modelValue) {
				this.$u.toast("请输入手机号")
				return
			}
			if (this.$refs.uCode.canGetCode) {
				this.$emit("time", dayjs().valueOf())
				// 模拟向后端请求验证码
				uni.showLoading({
					title: "正在获取验证码",
				})
				code({
					phone_sms: this.modelValue,
					tbId: this.tbId,
				})
					.then(res => {
						this.codeVisible = true
						console.log(this.code, "code")
					})
					.catch(err => {
						console.log(err)
						this.$u.toast(err.data.msg)
					})
				setTimeout(() => {
					uni.hideLoading()
					// 这里此提示会被this.start()方法中的提示覆盖
					this.$u.toast("验证码已发送")
					// 通知验证码组件内部开始倒计时
					this.$refs.uCode.start()
				}, 2000)
			} else {
				this.$u.toast("倒计时结束后再发送")
			}
		},
		end() {
			// this.$u.toast("倒计时结束")
		},
		start() {
			// this.$u.toast("倒计时开始")
		},
	},
	watch: {
		code(val) {
			if (val.length <= 6) this.$emit("change", val)
		},
	},
}
</script>
<style lang="scss" scoped>
.getCode {
	.phone {
		display: flex;
		align-items: center;
		gap: 10rpx;
	}
}
</style>
